/**
 * 
 */
package com.hexacta.hrs.web.struts.actions;

import java.util.EnumSet;

import org.apache.commons.lang.StringUtils;
import org.vectrics.common.util.DateUtil;
import org.vectrics.user.Person;

import com.hexacta.hrs.familiarrelationship.FamiliarRelationShipTypes;
import com.hexacta.hrs.familiarrelationship.FamiliarRelationship;
import com.hexacta.hrs.services.crud.CrudService;
import com.hexacta.hrs.services.employee.EmployeeService;
import com.hexacta.hrs.services.familiarrelationship.FamiliarRelationshipService;
import com.hexacta.hrs.util.Cuit;
import com.hexacta.hrs.util.Dni;

/**
 * @author mfunes
 * 
 */
public class FamiliarRelationshipAction extends CrudAbstractAction<FamiliarRelationship> {

    private static final long serialVersionUID = -430508390348886408L;

    private FamiliarRelationshipService familiarRelationshipService;

    private EmployeeService employeeService;

    private long employeeId;
    
    private long personId;

    private boolean editSelected;

    public boolean isEditSelected() {
        return editSelected;
    }

    public void setEditSelected(final boolean editSelected) {
        this.editSelected = editSelected;
    }

    public long getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(final long employeeId) {
        this.employeeId = employeeId;
    }

    public EmployeeService getEmployeeService() {
        return employeeService;
    }

    public void setEmployeeService(final EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    public void setFamiliarRelationshipService(final FamiliarRelationshipService familiarRelationshipService) {
        this.familiarRelationshipService = familiarRelationshipService;
    }

    public EnumSet<FamiliarRelationShipTypes> getFamiliarRelationShipTypes() {
        if (familiarRelationshipService.hasSpouse(employeeService.searchById(getEmployeeId())))
            return EnumSet.of(FamiliarRelationShipTypes.HIJA, FamiliarRelationShipTypes.HIJO, FamiliarRelationShipTypes.TUTORADO);
        return EnumSet.allOf(FamiliarRelationShipTypes.class);
    }

    @Override
    protected CrudService<FamiliarRelationship> getCrudService() {
        return familiarRelationshipService;
    }

    @Override
    protected void doActionsBeforeEdit() {
        editSelected = true;
        super.doActionsBeforeEdit();
    }
    
   

    @Override
    protected void doActionsBeforeSave() {
        FamiliarRelationship familiarRelationship = getModel();
        if (familiarRelationship.getEmployee() == null) {
            familiarRelationship.setEmployee(employeeService.searchById(getEmployeeId()));
        }
    }
    

    
    @Override
    protected FamiliarRelationship getSearchCriteria() {
    	
    	//seteo el employeeId a partir del personId
        this.obtainEmployeeId();
        
        FamiliarRelationship criteria = familiarRelationshipService.createNew();
        criteria.setEmployee(employeeService.searchById(getEmployeeId()));
        return criteria;
    }

	private void obtainEmployeeId() {
		if( this.getEmployeeId() == 0 && this.getPersonId() != 0) {
        	Person person = new Person();
        	person.setId(this.getPersonId());
        	this.setEmployeeId(this.getEmployeeService().searchByPerson(person).getId());
        }
	}

    @Override
    public void validate() {
        FamiliarRelationship familiarRelationship = getModel();
        boolean existsBday = true;
        boolean existsFtype = true;
        // Validaciones de Requerimiento.
        if (familiarRelationship.getBirthday() == null) {
            addFieldError("birthdayError", "Birthday is required");
            existsBday = false;
        }
        if (StringUtils.isEmpty(familiarRelationship.getFullName())) {
            addFieldError("nameError", "Name and LastName are required");
        }
        if (familiarRelationship.getFamiliarRelationshipType() == null) {
            addFieldError("rTypeError", "FamiliarRelationshipType is required");
            existsFtype = false;
        }
        boolean isValidCUIT = true;
        // Valida CUIT o CUIL
        if (!StringUtils.isEmpty(familiarRelationship.getCuilOrCuit())) {
            if (!Cuit.validar(familiarRelationship.getCuilOrCuit())) {
                addFieldError("cuiError", "CUIL invalid");
                isValidCUIT = false;
            }
        }
        boolean isValidDNI =true;
        // Valida el DNI
        if (!StringUtils.isEmpty(familiarRelationship.getDni()) &&!Dni.validar(familiarRelationship.getDni())) {
            addFieldError("dniError", "DNI invalid");
            isValidDNI = false;
        }
        
        //Valida que el DNI este dentro del CUIT/CUIL
        if(!StringUtils.isEmpty(familiarRelationship.getCuilOrCuit()) && isValidDNI && isValidCUIT){
            if(!familiarRelationship.getCuilOrCuit().contains(familiarRelationship.getDni())){
                addFieldError("dniError", "CUIL and DNI doesn't match.");
            }
        }
        
        // Valida la fecha de nacimiento que no sea superior o igual a la de hoy
        if (existsBday && DateUtil.mayorIgual(familiarRelationship.getBirthday(), DateUtil.getCurrentDate())) {
            addFieldError("datesError", "Birthday must be lower than the current date");
        }
        // verifica que el empleado no tenga 1 esposa. 
        //" super.getActionMethod() != null"  para asegurarme de que no entre a esta validacion cuando le doy a remove!!, no se si esta bien pero anda
           
        //seteo el employeeId a partir del personId.
        this.obtainEmployeeId();
        
        if (existsFtype && !editSelected &&  super.getActionMethod() != null)
        {
            if (familiarRelationship.getEmployee() == null)
            {
                familiarRelationship.setEmployee(employeeService.searchById(getEmployeeId()));
            }
            if (familiarRelationship.getFamiliarRelationshipType().equals(FamiliarRelationShipTypes.CONYUGE) && 
            		familiarRelationshipService.hasSpouse(familiarRelationship.getEmployee())) 
            {
                addFieldError("wifeError", "The employee already has a spouse");
            }
        }
        super.validate();
    }

	public void setPersonId(final long personId) {
		this.personId = personId;
	}

	public long getPersonId() {
		return personId;
	}

}
